/**
 * Created by aifece on 15/1/15.
 */

/**
 * 兼容的动画函数
 * animate(obj, { width:'100px' }, 2000, function(){ //... })
 * animate(obj, { width:'100px' }, 2000, 'ease', function(){ //... })
 * @author liw
 */
function animate(){
  var obj = arguments[0];
  if(!(obj instanceof jQuery)) {
    return;
  }
  var fn = Modernizr.csstransitions ? 'transition' : 'animate';
  var prop = arguments[1];
  if(!prop) return;
  for(var i in prop) {
    if(i.toLowerCase() == 'x' && fn == 'animate') {
      prop['left'] = prop[i];
      delete prop[i];
    } else if (i.toLowerCase() == 'y' && fn == 'animate') {
      prop['top'] = prop[i];
      delete prop[i];
    }
  }
  obj[fn].apply(obj, Array.prototype.slice.call(arguments, 1));
}

/**
 * 弹窗提示信息
 * param msg 提示文本
 * param status 提示状态 默认：warning ， 可选 success/error
 * param top 提示框距离浏览器顶部高度，默认 50%
 * param timeOut 提示框存在时间 默认 1500
 * 实例：showMsg('成功', 'success') showMsg('警告') showMsg('错误', 'error')
 */
function showMsg(msg, status, top, timeOut)
{
  var statusImg = 'prompt-icon3.png';
  if (status == 'success') {
    statusImg = 'prompt-icon2.png';
  } else if (status == 'error') {
    statusImg = 'prompt-icon1.png';
  }

  var html = '<div id="js_alertDiv"><div class="black-shade"></div><div class="float-common-prompt js_alertDivChild">\
    <dl>\
      <dt><img src="'+siteUrl+'/images/'+statusImg+'"></dt>\
      <dd>'+msg+'</dd>\
    </dl>\
  </div></div>';

  if ($('body').find('#js_alertDiv').length == 0) {
    $('body').append(html);
    var width = $('.float-common-prompt').width()+122;
    var height = $('.float-common-prompt').height()+102;
    $('.float-common-prompt').css({ marginLeft:-(width/2)+'px', marginTop:-(height/2)+'px' });
    if (width >= 660) {
      $('.float-common-prompt dd').css({ paddingTop:'0px' });
    } else {
      $('.float-common-prompt dd').css({ paddingTop:'15px' });
    }

    if (top) {
      $('#js_alertDiv>.js_alertDivChild').css({ top:top-0+80+'px' });
    }
  }

  if (!timeOut) {
    timeOut = 1000;
  }

  setTimeout(function(){
    $('#js_alertDiv').fadeOut('400', function() {
      $('#js_alertDiv').remove();
    });
  }, timeOut);
}

/**
 * 弹窗confirm
 * param msg 提示文本
 * param callback 点击确定后的回调函数
 * param callbackFail 点击取消后的回调函数
 * param hasBG 是否需要背景这招
 * 实例：showConfirm('您确定已满18岁', function(){ 'go' }, function(){ 'go' }) 
 */
function showConfirm(msg, callback, callbackFail, hasBG)
{
  var bg = '<div class="black-shade"></div>';
  if (hasBG === false) {
    bg = '';
  }
  var html = '<div id="js_confirmDiv">'+bg+'<div class="float-common-prompt2">\
      <a href="javascript:void(0);" class="close js_closeConfirm"></a>\
      <p class="text">'+msg+'</p>\
      <div class="btns"><a href="javascript:void(0);" class="btn-confirm js_submitConfirm">确定</a>\
      <a href="javascript:void(0);" class="btn-cancel js_cancelConfirm">取消</a></div>\
    </div>\
  </div>';

  if ($('body').find('#js_confirmDiv').length == 0) {
    $('body').append(html);

    $('#js_confirmDiv').on('click', '.js_submitConfirm', function(){
      if (callback) {
        callback();
      }
      $('#js_confirmDiv').fadeOut('400', function() {
        $('#js_confirmDiv').remove();
      });
      $('#js_confirmDiv').on('click', '.js_submitConfirm,.js_cancelConfirm,.js_closeConfirm', null);
    });
    $('#js_confirmDiv').on('click', '.js_cancelConfirm', function(){
      if (callbackFail) {
        callbackFail();
        btnClick('reset');
      }
      $('#js_confirmDiv').fadeOut('400', function() {
        $('#js_confirmDiv').remove();
      });
      $('#js_confirmDiv').on('click', '.js_submitConfirm,.js_cancelConfirm,.js_closeConfirm', null);
    });
    $('#js_confirmDiv').on('click', '.js_closeConfirm', function(){
      $('#js_confirmDiv').fadeOut('400', function() {
        $('#js_confirmDiv').remove();
      });
      $('#js_confirmDiv').on('click', '.js_submitConfirm,.js_cancelConfirm,.js_closeConfirm', null);
    });
  }
}

// 判断是否登录，没有登录弹出登陆框
function checkLogin(redirectUrl, callback)
{
  var url = siteUrl+'/user/check_login_status';
  $.post(url, {  }, function(json){
    if (json.info == 'ok') {
      if (callback) {
        callback();
      }
    } else {
      tollyRfUrl(redirectUrl); // 第三方登录
      $('.float-login-box').data('url', redirectUrl).data('login', '');
      $('.float-login-box').show().prev().show();
      //window.location.href = siteUrl+'/user/login?rfUrl='+redirectUrl;
    }
  }, 'json');
}

// 添加到购物车
function addGoodsToCart(skuId, goodsNum, callback, isPromotion, isGift)
{
  var url = siteUrl+'/cart/add_cart';
  var isP = 0;
  var isG = 0;
  if (isPromotion) {
    isP = 1;
  }
  if (isGift) {
    isG = 1;
  }
  $.post(url, { sku_id:skuId, goods_num:goodsNum, is_promotion:isP, is_gift:isG }, function(json){
    if (json.info == 'ok') {
      if (callback) {
        callback(json);
      }
    } else {
      showMsg(json.info);
    }
  }, 'json');
}

// 取滚动条高度
function getScrollTop()
{
    var scrollTop=0;
    if(document.documentElement&&document.documentElement.scrollTop)
    {
        scrollTop=document.documentElement.scrollTop;
    }
    else if(document.body)
    {
        scrollTop=document.body.scrollTop;
    }
    return scrollTop;
}

/**
 * 类Facebook图片居中
 * @param {jQueryobject} container 装载图片的外框，内部图片可相对其相对定位（relative）
 * @param number width 框的宽度
 * @param number height 框的高度
 * @author liw
 */
function imageCenters(containers, maxWidth, maxHeight, isLoading)
{
  if (!containers || !containers.length || !maxWidth || !maxHeight) {
    return false;
  }

  // 添加固定样式
  containers.css({
    overflow: 'hidden'
    //width: maxWidth+'px',
    //height: maxHeight+'px'
    //position: 'relative'
  });

  // 遍历
  $.each(containers, function(){
    var container = $(this);
    var imgObj = container.children('img').eq(0);
    var src    = imgObj.attr('src');
    if (!src) return true;
    imgObj.removeAttr("width").removeAttr("height");
    // loading
    if (isLoading) {
      imgObj.attr('src', '/images/loading.gif').css({
        'width': '16px',
        'height': '16px',
        'top': (maxHeight/2 - 8) + 'px',
        'left': (maxWidth/2 - 8) + 'px',
        'position': 'relative'
      });
    }
    // 加载图片
    loadImage(src, function(img){
      var width  = img.width;
      var height = img.height;

      if ( (width / height) >= (maxWidth/maxHeight) ) {
        var realW = (width / height) * maxHeight;
        var left = (realW -maxWidth) /2;
        imgObj.attr('src', src).attr('style', '').css({
          'height': maxHeight+'px',
          'left': '-' + left + 'px',
          'position': 'relative'
        });
      } else {
        var realH = (height / width) * maxWidth;
        var top = (realH-maxHeight) /2;
        imgObj.attr('src', src).attr('style', '').css({
          'width': maxWidth+'px',
          'top': '-' + top + 'px',
          'position': 'absolute'
        });
      }
    });
  });
}

/**
 * js 不被拦open
 */
function newWindowOpen(link)
{
  window.open(link, '_blank');
}

/**
 * 判断是否是safari 
 */
function is_safari()
{
  var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
  if (userAgent.indexOf("Safari") > -1) {
    return true;
  } //判断是否Safari浏览器

  return false;
}

/**
 * 过滤按钮重复点击
 * @param  {string} type 默认为按钮赋值 如：不传值或传 start 就是给当前按钮 添加 禁止重复点击事件  传reset 重置点击事件
 * @return {bool}   真/假
 */
function btnClick(type)
{
  if (!type || type == 'start') {
    if ($('body').data('btnClicked') == 1) {
      return false;
    }
    $('body').data('btnClicked', 1);
  }
  if (type == 'reset') {
    $('body').data('btnClicked', 0);
  }

  return true;
}

// 初始化
$(function(){
  // 公用链接跳转
  $('body').on('click', '.js_openLink', function(e){
    e.stopPropagation();
    
    var href = $(this).attr('data-href');
    var target = $(this).data('target');
    var isLogin = $(this).data('login');
    
    if (!href || href == '' || typeof href == 'undefind') {
      return false;
    }
    if (target == '_blank') {
      newWindowOpen(href);
      return;
    }
    if (isLogin == 1) {
      checkLogin(href, function(){
        window.location.href = href;
      });
    } else {
      window.location.href = href;
    }

    return false;
  });

  // 添加新商品到购物车
  $('body').on('click', '.js_addNewGoodsToCart', function(){
    var skuId = $(this).data('sku_id'); // skuId 可以是 1,2,3,
    var goodsNum = $(this).data('goods_num');
    /*
    new ActLo({
      P_x_0 : $(this).offset().left,
      P_y_0 : $(this).offset().top,
      P_x_1 : $('.operation .buy-car').offset().left,
      P_y_1 : $('.operation .buy-car').offset().top,
    });
    */
    if (!skuId) {
      return;
    }
    addGoodsToCart(skuId, 1, function(json){
      if (json.info == 'ok') {
        location.href = location.href;
      }
    }, 0);
  });
});